// Time:  O(n)
// Space: O(1)

#include <vector>

using namespace std;

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.empty()) {
            return 0;
        }

        const int k = 2; // At most k duplicated.

        int left = 0;
        int right = 1;

        while (right < nums.size()) {
            bool isDifferent = nums[left] != nums[right];
            bool withinFirstK = left - k + 1 < 0;
            bool underKOccurrences = nums[left] != nums[left - k + 1];
            
            if (isDifferent || withinFirstK || underKOccurrences) {
                nums[++left] = nums[right];
            }
            ++right;
        }

        return left + 1; 
    }
};
